<template>
  <van-button
    class="follow-btn"
    round
    size="small"
    :loading="isLoading"
    v-if="value"
    @click="followClick"
    >已关注</van-button
  >
  <van-button
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    :loading="isLoading"
    icon="plus"
    v-else
    @click="followClick"
    >关注</van-button
  >
</template>

<script>
import { addFollow,deleteFollow } from '@/api/user'
export default {
  name: "FollowUser",
  props:{
    // 是否被关注
    value:{
      type:Boolean,
      required:true
    },
    // 作者ID
    authorId:{
      type:[String,Number],
      required:true
    }
  },
  data() {
    return {
       isLoading:false // 是否处于等待中
    }
  },
  methods: {
    // 关注点击事件
    async followClick(){
      if(!this.$store.getters.token) return this.$toast.fail('请登录后操作！')
      // 开启loading
      this.isLoading = true
      // 是关注还是取消关注
      try {
        if(this.value){
          // 已关注，要取消
          await deleteFollow(this.authorId)
        }else{
          // 未关注，要关注
          await addFollow({
            target:this.authorId
          })
        }
        // 更新视图
        this.$emit('input', !this.value)
      } catch (error) {
        console.log(error);
        this.$toast.fail('操作失败')
      }
      // 关闭loading
      this.isLoading = false
    }
  },
};
</script>
<style></style>
